#include "thread_pool.h"

ThreadPool::ThreadPool(std::size_t n) {
    if (n == 0) n = 1;
    for (std::size_t i = 0; i < n; ++i) {
        workers_.emplace_back([this] {
            while (!stop_) {
                std::function<void()> task;
                {
                    std::unique_lock<std::mutex> lk(mutex_);
                    cv_.wait(lk, [this] { return stop_ || !tasks_.empty(); });
                    if (stop_ && tasks_.empty()) return;
                    task = std::move(tasks_.front());
                    tasks_.pop();
                }
                task();
            }
        });
    }
}

ThreadPool::~ThreadPool() {
    stop_ = true;
    cv_.notify_all();
    for (auto& t : workers_) {
        if (t.joinable()) t.join();
    }
}

void ThreadPool::enqueue(std::function<void()> task) {
    {
        std::lock_guard<std::mutex> lk(mutex_);
        tasks_.push(std::move(task));
    }
    cv_.notify_one();
}